package com.txc.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.txc.pojo.Root;
import com.txc.realms.RootRealms;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

@Configuration
public class ShiroConfig {

//    ShiroFilterFactoryBean:第三步
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);
        /**
         * anon:无需认证j就可以访问
         * authc:必须认证了才能访问
         * user:必须拥有 记住我 功能才能使用
         * perms:拥有对某个资源的权限才能访问
         * role:拥有某个角色权限才能访问
         */

        HashMap<String , String> Map = new HashMap<>();
        //必须认证了才能访问
        bean.setFilterChainDefinitionMap(Map);
        //访问失败默认走login页面
        bean.setLoginUrl("/toRootLogin");
        Map.put("/add","authc");
        Map.put("/delete","authc");
        Map.put("/update","authc");
        Map.put("/select","authc");
        //需要授权才能访问
        Map.put("/add","perms[Root]");
        Map.put("/delete","perms[Root]");
        Map.put("/update","perms[Root]");
        Map.put("/select","perms[Root]");
        //没授权跳转到未授权页面
        bean.setUnauthorizedUrl("/noauth");

        return bean;
    }

//    DafaultWebSecurityManager: 第二步
    @Bean(name="securityManager")
    public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("RootRealm")RootRealms rootRealms){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联Realm
        securityManager.setRealm(rootRealms);
        return securityManager;
    }

    //创建realm对象 需要自定义类  : 第一步
    @Bean
    public RootRealms RootRealm(){
        return new RootRealms();
    }

    //整合shiroDialect 用来整合整个shiro thymeleaf
    @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }


}
